"""
@Time : 2022/9/14 15:19 
@Author : ls
@DES: 
"""
import random
import time
from multiprocessing import Process, Manager, active_children, Queue


class Producer(Process):

    def __init__(self, queue, name):
        super().__init__()
        self.queue = queue
        self.name = name

    def run(self):
        for i in range(6):
            r = random.randint(0, 99)
            time.sleep(1)
            self.queue.put(r)
            print("放入队列  {}".format(r))
        self.queue.put(None)


class Consumer(Process):

    def __init__(self, queue, name):
        super().__init__()
        self.queue = queue
        self.name = name

    def run(self):
        while True:
            if not self.queue.empty():
                data = self.queue.get()
                print("取出队列  {}".format(data))
                if data is None:
                    break


if __name__ == '__main__':
    # q = Manager().Queue()  # 创建队列
    q = Queue()
    p = Producer(q, name='生产者')
    c = Consumer(q, name='消费者')
    p.start()
    c.start()
    print("活跃进程 %s " % active_children())  # 查看现有的进程
    p.join()
    c.join()
    print("结束")
    print("活跃进程 %s " % active_children())  # 查看现有的进程
